package top.lv666.graduation_design_serve.util;

import java.util.HashMap;
import java.util.Map;

public class CacheData {
    public static Map<String, Object> MEMORY_MAP = new HashMap<>();

    /**
     * @apiNote 在内存中储存MAP数据
     */
    public static void addCacheDate(String ip, String code, long expirationTime) {
        Map<String, Object> map = new HashMap<>();
        map.put("code", code);
        map.put("expirationTime", expirationTime);
        MEMORY_MAP.put(ip, map);
        System.out.println(MEMORY_MAP);
    }

    /**
     * @apiNote 判断内存数据
     */
    public static boolean checkCacheDate(String ip, String code) {
        try {
            long time = Tools.getTimer();
            Map<String, Object> map = (Map<String, Object>) MEMORY_MAP.get(ip);
            System.out.println(MEMORY_MAP);
            return code.equals(map.get("code")) && (long) map.get("expirationTime") + 300000 > time;
        } catch (Exception | Error e) {
            throw new Error("验证码错误！");
        }
    }

    /**
     * @apiNote 删除内存数据
     */
    public static void deleteCacheDate(String ip) {
        long time = Tools.getTimer();
        MEMORY_MAP.remove(ip);
        for (Map.Entry<String, Object> entry : MEMORY_MAP.entrySet()) {
            Map<String, Object> TempMap = (Map<String, Object>) entry.getValue();
            if ((long) TempMap.get("expirationTime") + 300000 < time) {
                MEMORY_MAP.remove(entry.getKey());
            }
        }
    }
}
